using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Utility = PHSRAG.Utility;
using DataAccess = PHSRAG.Utility.DataAccess;
using PHSRAG.Insight21.Humans;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using PHSRAG.Insight21.Policy;
using Header = PHSRAG.Insight21.InsightWebControls.Header;
using Annunciator = PHSRAG.WebControls.Annunciator;
using Pager = PHSRAG.WebControls.Pager;
using Utils = PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Insight21.CDS;
using PHSRAG.Insight21.Common.DownloadBarHelper;
using PHSRAG.Insight21.Common.Pages;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
	///	Provides main screen elements for active and inactive protocol tracking pages;
	/// </summary>
	public partial class ProtocolsControl : System.Web.UI.UserControl
	{
		#region Constants
		private const string ExcelReportControlFilePath = "../../Research/Reports/ProtocolsExcel.ascx";
        private const string AnimalsSortColumn = "SubmissionDate";
        private const string HumansSortColumn = "ProtocolNumber";
        #endregion

        #region Instance Variables (Private)       
		private int originatingPage;       
		private bool sortAscending = false;        
		#endregion
        
        
        #region Public Properties     

		/// <summary>
		/// Returns the breadcrumb control so the containing page can set its properties
		/// </summary>
        public PHSRAG.WebControls.BreadCrumb BreadCrumb
		{
			get{ return breadCrumb; }
		}

        /// <summary>
        /// Gets the boolean value, to decide whether or not to load the grid
        /// </summary>
        public bool IsOkayToLoadGrid
        {
            get
            {
                CommonSearchContext searchContext = ((Common.Pages.CachePage)Page).PrevailingCachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
                if (null == searchContext)
                {
                    return false;
                }

                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                UserContext userContext = ((Common.Pages.CachePage)Page).PrevailingCachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;

                return !(userContext.ShouldPromptForProtocolSearch(ModuleName) && searchCriteria.Version <= 0);
            }
        }
        
        /// <summary>
		/// This property will set the respective subnavigation link to be highlighted(This control as such will be used for Activeprotocols and InactiveProtocols)
		/// </summary>
        public string SelectedSubNavigationLink
		{
            set
            {
                if (ModuleName == InsightUtilities.Constants.Modules.Humans)
                    humansSubNavigation.SelectedLink = value;
                else
                    animalsSubNavigation.SelectedLink = value;
            }

        }
        #endregion

        #region Private Properties
        /// <summary>
        /// Sets the originating page context to pass along to the stored procedure that retrieves the protocols
        /// </summary>
        private int OriginatingPage
        {
            set { originatingPage = value; }
        }

        /// <summary>
        /// Date of the last successful feed that ran to populate this data
        /// </summary>
        private string LastFeedRunDate
        {
            get
            {
                string lastFeedRunDate = string.Empty;
                object feedDates = Application[InsightUtilities.Constants.FeedType.Cachekey];
                DataTable feedRunDates = (feedDates != null) ? (DataTable)feedDates : ProtocolManager.LastFeedRunDate;
                if (feedRunDates != null && feedRunDates.Rows.Contains(InsightUtilities.Constants.FeedType.HumansFeed))
                    lastFeedRunDate =((DateTime)feedRunDates.Rows.Find(InsightUtilities.Constants.FeedType.HumansFeed).ItemArray[0]).ToString("MM/dd/yyyy");
                return lastFeedRunDate;                
            }
        }
        /// <summary>
        /// Get the module name(from the header control)
        /// </summary>
        private string ModuleName
        {
            get
            {
                return header.ModuleName;
            }
        }
		
		/// <summary>
		/// Get the Protocols (summary of protocols) that the logged-in user has access to. The list of 
		/// protocols is maintained by the Protocols business object within its data container. 
		/// The Protocols object is cached.
		/// </summary>
        private ProtocolManager protocolManagerInstance
		{
			get
			{
				bool activePage = (Page is Humans.ActiveProtocols);
				// Determine the data to be fetched(Active or Inactive Protocols)
				int originatingContext = originatingPage = (activePage) ? 0 : 1;
                Humans.ProtocolManager protocolManager = ResultsCache;
                CommonSearchContext searchContext = (CommonSearchContext)((GridPage)this.Page).PrevailingCachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
				SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                UserContext userContext = ((GridPage)this.Page).PrevailingCachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
                
                if (protocolManager == null)
                {
                    protocolManager = new ProtocolManager(((GridPage)this.Page).PrevailingCachePolicy);
                    ((GridPage)this.Page).SortAscending = protocolManager.SortAscending = sortAscending;
                    protocolManager.SortColumn = (((GridPage)this.Page).SortColumn == null) ? (ModuleName == InsightUtilities.Constants.Modules.Humans) ? HumansSortColumn : AnimalsSortColumn :
                                                 ((GridPage)this.Page).SortColumn ;

                    protocolManager.GetActiveInactiveProtocolIds(
                                        DataAccess.ConnectionString,
                                        searchCriteria,
                                        userContext.DomainUserId,
                                        originatingContext,
                                        (ModuleName == InsightUtilities.Constants.Modules.Humans) ? Constants.ModuleType.Humans : Constants.ModuleType.Animals);
                }         
				return protocolManager;                  		
			}            
		}

                      
        /// <summary>
        /// Gets the protocolManager objects from the results cache 
        /// Note: The protocol manager gets refreshed with each search or action that triggers the search(eg Sorting etc.)
        /// </summary>
        private ProtocolManager ResultsCache
        {
          
           get
            {
                return Policy.ResultsCache.GetObject(((GridPage)this.Page).PrevailingCachePolicy, ProtocolManager.CacheKey) as ProtocolManager;
            }
           
        }
		#endregion

		#region constants
		private const string AttachmentType="ATCHTYPE_CNSNTFRM";
		private const string AnnunciatorTitle = "The following error(s) occurred...";
		#endregion

		#region Event Handlers

		#region Pager Event Handlers
        
		/// <summary>
		/// Occurs when the FirstPage hyperlink is clicked on the pager.
		/// The page's DataGrid is reloaded with the data belonging to the first page.
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnFirstPage(object sender, CommandEventArgs e)
		{
            ((GridPage)this.Page).CurrentPageIndex = 0;
            LoadDataGrid();
		}

		/// <summary>
		/// Occurs when the LastPage hyperlink is clicked on the pager.
		/// The page's DataGrid is reloaded with the data belonging to the last page.
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnLastPage(object sender, CommandEventArgs e)
		{
			int lastPageIndex = topPager.PageCount - 1;
            ((GridPage)this.Page).CurrentPageIndex = lastPageIndex;
            LoadDataGrid();
		}

		/// <summary>
		/// Occurs when the NexttPage hyperlink is clicked on the pager.
		/// The page's DataGrid is reloaded with the data belonging to the next page.
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnNextPage(object sender, CommandEventArgs e)
		{
            ++((GridPage)this.Page).CurrentPageIndex;
            LoadDataGrid();
		}

		/// <summary>
		/// Occurs when the PreviousPage hyperlink is clicked on the pager.
		/// The page's DataGrid is reloaded with the data belonging to the previous page.
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnPreviousPage(object sender, CommandEventArgs e)
		{
            --((GridPage)this.Page).CurrentPageIndex;
            LoadDataGrid();
		}

		/// <summary>
		/// This event is raised when the page index property is changed on the pager control.
		/// The page's DataGrid is reloaded with the data belonging to page specified by the index.
		/// </summary>
		/// <param name="source">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
		private void OnPageIndexChanged(object source, DataGridPageChangedEventArgs e)
		{
			protocolsGrid.CurrentPageIndex = e.NewPageIndex;
            LoadDataGrid();
		}

		#endregion Pager Event Handlers

		/// <summary>
		/// Initiates the search by calling PerformSearch
		/// </summary>
		/// <param name="args">Argument associated with the event (contains the search criteria dictionary)</param>
		protected void OnSearch(SearchCriteriaArgs args)
		{
			try
			{
                PerformSearch();
			}
			catch(System.Data.EvaluateException ex)
			{
				gridContainer.Visible = false;
				if (ex.Message.IndexOf("Error in Like operator:") >= 0 )
				{
					annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
					annunciator.Message = "Search Error: Wild card character(%) can either be specified at the beginning or end of the criterion.";
				}
				else
				{
					Utility.ExceptionReport.WriteToEventLog("ProtocolsControl OnSearch", ex, true, Utility.ExceptionReport.ReportType.Error);
					DisplayExceptionReport(ex);
				}
			}
			catch(Exception ex)
			{
				gridContainer.Visible = false;
				Utility.ExceptionReport.WriteToEventLog("ProtocolsControl OnSearch", ex, true, Utility.ExceptionReport.ReportType.Error);
				DisplayExceptionReport(ex);
			}
		}

        

		/// <summary>
		/// Handler for the event raised by the CommonSearch control when the "Clear Selection" buttion is clicked upon.
		/// The control clears the criteria (specific to this module).
		/// Since in the page life-cycle, the Load occurs before the Clear event, we have to instigate a re-load of the
		/// data grid to refelect the fact that the search criteria has been cleared.
		/// </summary>
		/// <param name="sender">Sender of the event</param>
		/// <param name="e">Argument associated with the event</param>
		protected void OnClearSelection(object sender, CommandEventArgs e)
		{
            protocolsGrid.DataSource = null;
            protocolsGrid.DataBind();
            HideGrid();
            annunciator.Message = @"Verify the search criteria and click the 'Search' button to return the matching records.";
            // We need to completely clear the search criteria for the module because we 
            // depend on version 0 to know if it's ok to load the grid.  We can't set the version
            // back to 0 due to the design of search context.
            CommonSearchContext searchContext = ((GridPage)this.Page).PrevailingCachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            searchContext.ClearModuleSearchCriteria();
        }

		/// <summary>
		/// On non-postbacks, search criteria is retrieved and the datagrid is loaded with protocols.  
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
			try
			{                
                /*at098- 01/21/2008
                 * SQL reports
                 * Active and Inactive protocol reports between humans and animals are being separated out. This is because of 
                 different requirements and easier maintenance moving forwards.*/
                if (((GridPage)this.Page).PageCacheKey == Keys.ActiveProtocolsPageKey) 
                {
                    downloader.SQLReportName = SSRSRequest.ReportNames.Humans.ActiveProtocols;
                }
                else if (((GridPage)this.Page).PageCacheKey == Keys.AnimalsActiveProtocolsPageKey)
                {
                    downloader.SQLReportName = SSRSRequest.ReportNames.Animals.ActiveProtocols;
                }
                else if (((GridPage)this.Page).PageCacheKey == Keys.InactiveProtocolsPageKey )
                {
                    downloader.SQLReportName = SSRSRequest.ReportNames.Humans.InActiveProtocols;
                }
                else if (((GridPage)this.Page).PageCacheKey == Keys.AnimalsInactiveProtocolsPageKey)
                {
                    downloader.SQLReportName = SSRSRequest.ReportNames.Animals.InActiveProtocols;
                }
                SetAnimalsOrHumansControls();

				annunciator.EnableViewState = false;			
				if (!IsPostBack && postbackGuard.IsValid) 
				{
                    //if (((Common.GridBasePage)this.Page).SortColumn == null)
                        ((GridPage)this.Page).SortColumn = (((GridPage)this.Page).SortColumn == null) ? (ModuleName == InsightUtilities.Constants.Modules.Humans) ? HumansSortColumn : AnimalsSortColumn :
                                                 ((GridPage)this.Page).SortColumn;
                   
                    Policy.ResultsCache.PurgeObject(((GridPage)this.Page).PrevailingCachePolicy);
                    protocolsGrid.PageSize = Utility.Settings.GetKeyValue("HumansDataGrid.ItemsPerPage", 20);
   				
					((WebControls.ExpansionToggler)humansSearchContainer.FindControl("humansExpansionToggler")).HelpText =
                        ((WebControls.ExpansionToggler)animalsSearchContainer.FindControl("animalsExpansionToggler")).HelpText = 
						InsightUtilities.Constants.SearchHelpText + InsightUtilities.Constants.FilterHelpText;

                    if (IsOkayToLoadGrid)
                        LoadDataGrid();                                 
				} 
                
			}
			catch(System.Data.EvaluateException ex)
			{
				if (ex.Message.IndexOf("Error in Like operator:") >= 0 )
				{
					gridContainer.Visible = false;
					annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
					annunciator.Message = "Search Error: Wild card character(%) can either be specified at the beginning or end of the criterion.";
				}
				else
				{
					Utility.ExceptionReport.WriteToEventLog("ProtocolsControl Load", ex, true, Utility.ExceptionReport.ReportType.Error);
					DisplayExceptionReport(ex);
				}
			}
			catch(Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("ProtocolsControl Load", ex, true, Utility.ExceptionReport.ReportType.Error);
				DisplayExceptionReport(ex);
			}
		}

		
		/// <summary>
		/// Hides the PendingIRB column if this is the InactiveProtocols page
		/// </summary>
		/// <param name="sender">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnDataBound(object sender, System.EventArgs e)
        {
            protocolsGrid.Columns[(int)ColumnIndex.PendingIRB].Visible =
                protocolsGrid.Columns[(int)ColumnIndex.viewConsent].Visible =
                (Page is ActiveProtocols);
            if (ModuleName == InsightUtilities.Constants.Modules.Animals && Page is ActiveProtocols)
            {   protocolsGrid.Columns[(int)ColumnIndex.PendingIRB].HeaderText = "Pending Review";
                protocolsGrid.Columns[(int)ColumnIndex.viewConsent].Visible = false;
            }           
        }
        		
		/// <summary>
		/// Handles events raised by clicking on items in the grid.  If the command associated with the event
		/// If "SelectProtocol", data relevant to the details page is stored to session and the page
		///		is redirected to protocol details page.
		///	If "openConsent", data will be cached and
		///		redirected to consent form selection page (if consent form count >1)
		///		else the consent form is opened directly as a popup.
		/// </summary>
		/// <param name="source">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try 
			{
				Hashtable outgoingData = new Hashtable();
				outgoingData.Add(Keys.ProtocolIdKey, e.Item.Cells[(int) ColumnIndex.Id].Text);
				outgoingData.Add(Keys.ProtocolAccessKey, e.Item.Cells[(int) ColumnIndex.AccessLevel].Text);
				if (e.CommandName == "SelectProtocol")
				{
					((GridPage)this.Page).PrevailingPageCachePolicy.Cache(Keys.ShowNewProcessBarKey, true);
					((GridPage)this.Page).PrevailingPageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
					PurgeCache();
					Page.Response.Redirect(
						Utility.Settings.GetKeyValue("SubModuleNavigation.Humans.ProtocolDetailsURL",""),false);
				}
				else if (e.CommandName == "openConsent")
				{
					outgoingData.Add(Keys.ConsentCountKey, int.Parse(e.Item.Cells[(int)ColumnIndex.ConsentFormCount].Text));
					((GridPage)this.Page).PrevailingPageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

					int consentFormCount = int.Parse(e.Item.Cells[(int)ColumnIndex.ConsentFormCount].Text);
					if (consentFormCount > 1)
					{	
						LaunchConsentFormSelectionPage();
					}
					else if(consentFormCount == 1)
					{
						ShowConsentForm(int.Parse(e.Item.Cells[(int) ColumnIndex.Id].Text));
					}											
				}				
			}
			catch ( Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog("ProtocolsControl OnItemCommand", ex, true, Utility.ExceptionReport.ReportType.Error);
				DisplayExceptionReport(ex);
			}
		}

	
		/// <summary>
		/// Handler for event raised while each data grid item is created.
		/// If the item being created is the data grid header, do the following:
		/// Add the appropriate sort symbol to denote ascending/descending sequence for the current sort column.
		/// This requires us to locate the cell which corresponding to the column within the collection of TableCell
		/// maintained by the DataGridItem which is under creation. That collection is indexed numerically, the value being
		/// the position of the column within the columns collection maintained by the data grid.
		/// One simple way to do this is to create static mapping between the name of the column and its index. However, this
		/// suffers from the shortcoming that if the sequence of columns is changed on the page, the static binding MUST
		/// be changed too. If they get out of sync, we would be sorting on inappropriate columns!
		/// To avoid this, and to render the code independent of how the page gets managed, we will build a Hashtable of
		/// column indeces, keyed by the sort expression of each column. That way, we could do a quick lookup to get the
		/// index of a column and set the sort symbol on that column.
		/// If the item being created is a data row item, disable its view state.
		/// </summary>
		/// <param name="sender">Control which raised the event</param>
		/// <param name="e">Argument associated with the event</param>
		protected void OnItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
            if (e.Item.ItemType == ListItemType.Header)
            {
                ProtocolManager protocolManager = protocolManagerInstance;
                Label sortSymbol = new Label();
                sortSymbol.Text = protocolManager.SortAscending ? Utils.Constants.SortAscendingText : Utils.Constants.SortDescendingText;
                sortSymbol.Font.Name = Utils.Constants.SortSymbolFontName;

                Hashtable columnMap = new Hashtable();
                foreach (DataGridColumn column in protocolsGrid.Columns)
                    columnMap[column.SortExpression] = protocolsGrid.Columns.IndexOf(column);                                        
               
                string sortColumn = protocolManager.SortColumn;
                if (columnMap.ContainsKey(sortColumn))
                    ((TableCell)e.Item.Cells[(int)columnMap[sortColumn]]).Controls.Add(sortSymbol);             
                
            }
            		
		}

		/// <summary>
		/// Handles events raised by sorting the datagrid.  Processes the sort criteria and if the column to sort
		/// on is different than the column currently sorted on, the protocols and their ids are unloaded from the
		/// cache.  In all cases, the search criteria is retrieved, the grid is loaded with the protocols, and
		/// the sort arrow is displayed on the appropriate column in the appropriate direction.  
		/// </summary>
		/// <param name="source">The object raising an event.</param>
		/// <param name="e">Argument associated with the event</param>
        protected void OnSort(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			if (e.SortExpression != string.Empty)
			{
                ProtocolManager protocolManager = ResultsCache;
                if (protocolManager != null)
                {
                   sortAscending = (protocolManager.SortColumn == e.SortExpression) ? !protocolManager.SortAscending : false;
                }
                ((GridPage)this.Page).SortColumn = e.SortExpression;
                PerformSearch();
			}
		}


		/// <summary>
		/// Purges the cache and resets the selected subnavigation link before the 
		/// header performs a redirect.
		/// </summary>
		/// <param name="sender">Control which rasied the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
		{
			PurgeCache();
			humansSubNavigation.Reset();
            animalsSubNavigation.Reset();            
		}

		/// <summary>
		/// Purges the cache before the humans subnavigation header performs a redirect.
		/// </summary>
		/// <param name="sender">Control which rasied the event.</param>
		/// <param name="e">Arguments associated with the event.</param>
        protected void OnSubNavigate(object sender, CommandEventArgs e)
		{
			PurgeCache();
		}

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = Utility.ExceptionReport.GetExceptionInfo((Exception)e.CommandArgument, false);
        }
                     
		#endregion

		#region Private Methods
        /// <summary>
        /// Gets the ProtocolDocument by passing the protocolId. calls the LaunchConsentForm() to open the ConsentForm Output
        /// </summary>
        /// <param name="protocolId">the protocolId corresponding to the document</param>
        private void ShowConsentForm(int protocolId)
        {
            ProtocolDocument protocolDocument =
                (ProtocolDocument)Protocol.GetPublishedConsentForms(protocolId, AttachmentType, ((GridPage)this.Page).PrevailingCachePolicy)[0];
            if (protocolDocument != null)
            {
				LaunchConsentForm(UIUtility.GetConsentFormWithFooter(new NullCachePolicy(), protocolDocument));
            }
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Retrieves the CommonSearchContext from the cache.  If it's not null, a search is initiated on the
        /// ProtocolSummaries object using the search criteria; the fact that the protocols have been filtered gets 
        /// cached, the dataGrid page gets reset to 0, the grid gets loaded and the pagers get initialized.
        /// </summary>
        private void PerformSearch()
        {
            Policy.ResultsCache.PurgeObject(((GridPage)this.Page).PrevailingCachePolicy);
            // We check for criteria version 0 to conditionally not load the data grid
            // for users with access to many protocols.  Since we're searching, increment 
            // the version number 
            CommonSearchContext searchContext = ((GridPage)this.Page).PrevailingCachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
            searchCriteria.Version++;
            searchContext.SetSearchCriteria(Page.Request.Url.ToString(), searchCriteria, searchContext.GetSearchCriteria(Page.Request.Url.ToString()));

            ((GridPage)this.Page).CurrentPageIndex = protocolsGrid.CurrentPageIndex = 0;
            LoadDataGrid();
            InitializePager();
        }

        /// <summary>
        /// Launches the consent form with the related document footer
        /// </summary>
        /// <param name="document">protocolDocument object</param>
        private void LaunchConsentForm(Document document)
        {
            Hashtable outgoingData = new Hashtable();
            outgoingData[Keys.DocumentKey] = document;
            ((GridPage)this.Page).PrevailingCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

            string script = "\n<script language=JavaScript id='Display'>\n" +
				"var confirmWin = window.open('../Research/DownloadForm.aspx', 'ViewFile', 'resizable=yes, status=yes, toolbar=no, scrollbars=yes'); \n" +
                "</script>";

            if (!Page.ClientScript.IsClientScriptBlockRegistered("Display"))
            {
                //Register the script
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "Display", script);
            }
        }

        /// <summary>
        /// Launches the consent form Selection page 
        /// </summary>
        private void LaunchConsentFormSelectionPage()
        {
            string script = "\n<script language=JavaScript id='Display'>\n" +
				"var confirmWin = window.open('../Research/ConsentFormSelectionPage.aspx', 'SelectConsentForm', 'resizable=yes, status=yes, toolbar=no, scrollbars=yes, width=500, height=300'); \n" +
                "</script>";

            if (!Page.ClientScript.IsClientScriptBlockRegistered("Display"))
            {
                //Register the script
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "Display", script);
            }
        }
		/// <summary>
		/// Load the datagrid with sufficient data for display within one page of the data grid. This is done as follows:
		/// Get the summaries for all protocols that the user has access to. Use that to initialize the data grid and
		/// the pager controls based on the page size of the data grid.
		/// The pagers are made visible only when more than one page of data can be displayed.
		/// If there is no data to display, warn the user via the annunciator, and turn the visibility
		/// on the panel containing the datagrid off
		/// </summary>
		private void LoadDataGrid()
		{ 
			try
			{
				ProtocolManager protocolManager = protocolManagerInstance;
                if (protocolManager != null)
                {
                    int totalRecordCount = protocolManager.Count;
                    if (totalRecordCount > 0)
                    {
                        topPager.Visible = bottomPager.Visible = true;
                        protocolsGrid.VirtualItemCount =
                            bottomPager.RecordCount = topPager.RecordCount =
                            totalRecordCount;
                        pageLabel.Text = String.Format("{0} {1} | As Of {2}", totalRecordCount,
                            (Page is ActiveProtocols) ? "Active Protocols" : "Inactive Protocols",
                            LastFeedRunDate);
                        int currentPageIndex = ((GridPage)this.Page).CurrentPageIndex;
                        int pageCount = (topPager.RecordCount / protocolsGrid.PageSize) +
                            (int)(((topPager.RecordCount % protocolsGrid.PageSize) == 0) ? 0 : 1);
                        bottomPager.PageCount = topPager.PageCount = pageCount;
                        bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;
                        UserContext userContext = ((GridPage)this.Page).PrevailingCachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;                        

                        /*at098 - 02/08/2008
                         * The sql datareader is bound to the datagrid directly. The object collection is avoided.
                         */
                        //ArrayList protocolList = protocolManager.GetProtocolDetails(currentPageIndex * protocolsGrid.PageSize, Math.Min(currentPageIndex * protocolsGrid.PageSize + protocolsGrid.PageSize, totalRecordCount), DataAccess.ConnectionString, userContext.DomainUserId);
                        try
                        {
                            //int totalCount = protocolManager.Count;
                            //int endIndex = Math.Min(currentPageIndex * protocolsGrid.PageSize + protocolsGrid.PageSize, totalRecordCount);
                            //if (totalCount < endIndex || (totalCount == 1 && endIndex == 1))
                            //{
                            //    PurgeCache();
                            //    LoadDataGrid();
                            //}
                           SqlDataReader rdr = protocolManager.GetProtocolDetails(currentPageIndex * protocolsGrid.PageSize, Math.Min(currentPageIndex * protocolsGrid.PageSize + protocolsGrid.PageSize, totalRecordCount), DataAccess.ConnectionString, userContext.DomainUserId);
                                protocolsGrid.DataSource = rdr;
                                protocolsGrid.DataBind();
                                rdr.Close();
                                if (ModuleName == InsightUtilities.Constants.Modules.Humans)
                                    protocolsGrid.Columns[(int)ColumnIndex.SubmissionDate].Visible = false;
                            
                        }
                        catch 
                        {
                            throw new Exception("Your Search is out of context. Please use a different search criteria.");                            
                        }                      
                        
                        /*at098 - changes end*/

                        if (protocolsGrid.Items.Count == 0)
                             HideGrid();
                        else
                        {                            
                            ShowGrid();
                            if (((GridPage)this.Page).CurrentPageIndex == 0)
                                InitializePager();
                            ManagePagination();
                            ManageNavigationLinks();
                        }
                    }
                    else
                        HideGrid();
                }
                else
                    HideGrid();           

			}
			catch (Exception e)
			{
				Utility.ExceptionReport.WriteToEventLog("ProtocolsControl LoadDataGrid", e, true, Utility.ExceptionReport.ReportType.Error);
				gridContainer.Visible = false;
                searchCriteriaDisplay.Visible = false;
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = "Your Search is out of context. Please use a different search criteria.";
			}
		}
        /// <summary>
        /// This method shows the grid
        /// </summary>
        private void ShowGrid()
        {
            gridContainer.Visible = true;
            annunciator.Message = string.Empty;
        }

        /// <summary>
        /// This method hides the grid
        /// </summary>
        private void HideGrid()
        {
            topPager.Visible = bottomPager.Visible = false;
            gridContainer.Visible = false;
            annunciator.Message = "The search criteria yielded no results.";
        }

        private void SetAnimalsOrHumansControls()
        {
            if (ModuleName == InsightUtilities.Constants.Modules.Humans)
            {
                humansSubNavigation.Visible = humansSearchContainer.Visible = true;
                animalsSearchContainer.Visible = animalsSubNavigation.Visible = false;
            }
            else
            {
                animalsSearchContainer.Visible = animalsSubNavigation.Visible = true;
                humansSubNavigation.Visible = humansSearchContainer.Visible = false;
            }
        }

		/// <summary>
		/// Initilize the first record, last record and current page values for the pager controls.
		/// Set the current page index to 0 and manage navigation links.
		/// </summary>
		private void InitializePager()
		{
			bottomPager.FirstRecord = topPager.FirstRecord = 1;
			bottomPager.LastRecord = topPager.LastRecord = 
				Math.Min(protocolsGrid.PageSize, protocolsGrid.Items.Count);
			bottomPager.CurrentPage = topPager.CurrentPage = 1;
            ((GridPage)this.Page).CurrentPageIndex = 0;
			ManageNavigationLinks();
		}

		/// <summary>
		/// Enables or Disables links to other pages within the grid
		/// </summary>
		private void ManageNavigationLinks()
		{
			bottomPager.EnableFirstPage = topPager.EnableFirstPage = 
				bottomPager.EnablePreviousPage = topPager.EnablePreviousPage = 
				(protocolsGrid.CurrentPageIndex != 0);

			bottomPager.EnableLastPage = topPager.EnableLastPage = 
				bottomPager.EnableNextPage = topPager.EnableNextPage = 
				(protocolsGrid.CurrentPageIndex != (topPager.PageCount - 1));
		}

		
		/// <summary>
		/// Determine first and last number of the displaying records
		/// </summary>
		private void ManagePagination()
		{
            int currentPageIndex = ((GridPage)this.Page).CurrentPageIndex;
			protocolsGrid.CurrentPageIndex = currentPageIndex;

			int startIndex = currentPageIndex * protocolsGrid.PageSize;
			bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

            int lastRecord = protocolManagerInstance.Count;
			bottomPager.LastRecord = topPager.LastRecord =
				Math.Min(startIndex + protocolsGrid.PageSize, lastRecord);
		}

		/// <summary>
		/// Uncaches all objects with data for this page.
		/// </summary>
		private void PurgeCache() 
		{
			System.Diagnostics.Trace.WriteLine("Purging ProtocolSummaries...");
            Policy.ResultsCache.PurgeObject(((GridPage)this.Page).PrevailingCachePolicy);
            humansSubNavigation.Reset();
            animalsSubNavigation.Reset();
		}

        #endregion

		#region Web Form Designer generated code

		///<summary>Initializes components used by the page.</summary>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			//InitializeComponent();
            if (Page is ActiveProtocols)
                ((GridPage)this.Page).PageCacheKey =
                    (ModuleName == InsightUtilities.Constants.Modules.Humans) ? Keys.ActiveProtocolsPageKey :
                                                            Keys.AnimalsActiveProtocolsPageKey;
            else
                ((GridPage)this.Page).PageCacheKey =
                    (ModuleName == InsightUtilities.Constants.Modules.Humans) ? Keys.InactiveProtocolsPageKey :
                                                            Keys.AnimalsInactiveProtocolsPageKey;

			base.OnInit(e);        
		
			humansSubNavigation.Navigate += new CommandEventHandler(OnSubNavigate);
			this.downloader.FailedAction += new CommandEventHandler(OnDownloadFailed);

            newProtocolBar.ModuleName = ModuleName;
		}
				
		#endregion

		#region ColumnIndex Enum
		/// <summary>
		/// Provides indexes used in the datagrid for specific columns
		/// </summary>
		private enum ColumnIndex
		{
			/// <summary>id column index (hidden)</summary>
			Id,
			/// <summary>access level column index (hidden)</summary>
			AccessLevel,
			/// <summary>protocol # column index</summary>
			ProtocolNumber,
			/// <summary>pi's name column index</summary>
			PINname,
			/// <summary>title column index</summary>
			Title,
			/// <summary>Sponsor Name column index</summary>
			SponsorName,
			/// <summary>overall status column index</summary>
			OverallStatus,
			/// <summary>Consent Form column index</summary>
			viewConsent,
			/// <summary>pendingIRB column</summary>
			PendingIRB,
            ///<summary>SubmissionDate</summary>
            SubmissionDate,
			/// <summary>expiration date column index</summary>
			Expirationdate,			
            /// <summary>ConsentFormCount</summary>
			ConsentFormCount
			
		}
		#endregion
	}
}
